package swimv2gm.client.user;

import java.io.IOException;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.session.UserManager;

/**
 * Prepara i dati relativi ad un utente per la visualizzazione o la modifica del
 * suo profilo.
 * 
 * @author Matteo Gallesio
 */
public class Profile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		UserManager man;
		try {
			man = (UserManager)InitialContext.doLookup("UserManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		String uid_p = request.getParameter("uid");
		long uid = 0;
		try {
			uid = Long.parseLong(uid_p);
		} catch (NumberFormatException e) {
			request.setAttribute("userData",null);
			request.getRequestDispatcher("profile.jsp").forward(request,response);
			return;
		}

		String action = request.getParameter("action");
		if (action == null)
			action = "show";
		String nextPage = "profile.jsp";

		Map<String,String> userData = man.getUserData(uid);
		request.setAttribute("userData",userData);

		if (action.equalsIgnoreCase("show")) {
			Map<Long,String> abilities = man.getAbilities(uid);
			request.setAttribute("abilities",abilities);
		}

		// don't allow editing of other users' profiles
		else if (action.equalsIgnoreCase("edit")) {
			if (new Long(uid).equals(request.getSession().getAttribute("user"))) {
				nextPage = "edit.jsp";
			}
			else {
				response.sendError(403);
				return;
			}
		}

		request.getRequestDispatcher(nextPage).forward(request,response);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doGet(request,response);
	}
}